const mainUrl = getApp().globalData.websiteUrl;
//把配置项单独处理
function httpSevice(options = {}) {
    // token = service.getToken()
    options.url = `${mainUrl}${options.url}`;
	// console.log(options.url)
          //配置请求头
    // options.header = {
    //     'content-type':'application/x-www-form-urlencoded'
    // };
	let token = uni.getStorageSync('tokey');  //凭证
	if(token){
		options.header = {
		    'X-Token':token
		};
	}
	uni.showLoading({
		title:'正在请求...',
		mask: true
	});
    return new Promise((resolved, rejected) => {
        //成功
        options.success = (res) => {
			// console.log(res)
			uni.hideLoading();
            if (Number(res.statusCode) == 200) {  //请求成功
				let resData = res.data;
				if(resData.message == "无token，请重新登录" || resData.code == "token过期"){
					uni.navigateTo({
					    url: '/pages/index/login'
					});
				}else{
					resolved(resData);
				}
                
            } else {
                // uni.showToast({
                //     icon: 'none',   
                //     duration: 3000,
                //     title: `${res.errMsg}`
                // });
                rejected(res.errMsg);//错误
            }
        }
        //错误
        options.fail = (err) => {
			uni.hideLoading();
            rejected(err.errMsg); //错误
        }
        uni.request(options);
    });
}
async function upImage (param){//普通上传
    let image = await uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    });
    let result = await uni.uploadFile({
        url: mainUrl + '/public/upload', //仅为示例，非真实的接口地址
        filePath: image[1].tempFilePaths[0],
        name: 'file',
        // header: {
        //     'X-Token': token
        // },
        formData: param,
    });
    return result;
}
module.exports = {
	httpSevice,
	mainUrl,
    upImage
}